package com.helloandroid.paso.ui.mediaplayer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.os.AsyncTask;
import android.text.TextUtils;

public class FileDownloader extends AsyncTask<String, Void, String> {
	
	private IFileDownloaderCallback callback;
	
	public FileDownloader(IFileDownloaderCallback callback){
		this.callback = callback;
	}
	
	@Override
	protected String doInBackground(String... params) {
		String fileContents = null;
		try {
			fileContents = downloadFile(params[0]);
		} catch (IOException e) {
			callback.onFailure();
		} catch(IllegalStateException e){
			callback.onFailure();
		}
		
		return fileContents;
	}
	
	@Override
	protected void onPostExecute(String contents){
		if(!TextUtils.isEmpty(contents))
			callback.onSucces(contents);
	}
	
	private String downloadFile(String url) throws IllegalStateException, IOException{
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet, localContext);
		String result = "";
		 
		BufferedReader reader = new BufferedReader(
		    new InputStreamReader(
		      response.getEntity().getContent()
		    )
		  );
		 
		String line = null;
		while ((line = reader.readLine()) != null){
		  result += line + "\n";
		}
		
		return result;
	}

}
